package com.harmontronics.hanma.paas.paas.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.harmontronics.hanma.paas.paas.domain.app.entity.HmPage;
import com.harmontronics.hanma.paas.paas.domain.app.service.HmPageService;
import com.harmontronics.hanma.paas.paas.domain.iam.entity.HmMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.harmontronics.hanma.paas.paas.domain.iam.service.HmMenuService;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("hmMenuAppService")
@DS("#header.App-Unique")
public class HmMenuAppService extends HmMenuService {

    @Autowired
    private HmPageService hmPageService;

    @Override
    public HmMenu findById(Long id) {
        HmMenu hmMenu = super.findById(id);

        if (hmMenu != null && hmMenu.getPageId() != null) {
            HmPage hmPage = hmPageService.findById(hmMenu.getPageId(), false);
            hmMenu.setPageName(hmPage.getName());
        }

        return hmMenu;
    }

    @Override
    public List<HmMenu> getList() {
        List<HmMenu> hmMenus = super.getList();
        hmMenus.sort(Comparator.comparing(HmMenu::getSerialNum,Comparator.nullsLast(Integer::compareTo)));
        List<Long> pageIds = hmMenus.stream().filter(e -> e.getPageId() != null).map(HmMenu::getPageId).collect(Collectors.toList());
        List<HmPage> pages = hmPageService.findByIds(pageIds, false);
        for (HmMenu hmMenu : hmMenus) {
            if (hmMenu.getPageId() == null) {
                continue;
            }
            for (HmPage page : pages) {
                if (page.getId().longValue() == hmMenu.getPageId().longValue()) {
                    hmMenu.setPageName(page.getName());
                }
            }
        }
        return hmMenus;
    }
}